package com.zhongshengnetwork.rightbe.my.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.Region.RegionSelectActivity;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.dbservice.LogindbService;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

//三检查OK:2016-11-30
public class MyAreaActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{
    private static final int REGION_REQUEST_CODE = 001;
    private TopBarView topbar;
    private ListView listview;
    boolean isLocating;
    private String location = "";
    private MyAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBoradcastReceiver();
        setContentView(R.layout.activity_my_area);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        topbar.getRightTextView().setVisibility(View.VISIBLE);
        topbar.getRightTextView().setText("保存");
        topbar.getRightTextView().setTextSize(16);
        topbar.getRightTextView().setClickable(true);
        topbar.getRightTextView().setTextColor(getResources().getColor(R.color.defaultLightColor));
        topbar.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonUtils.isEmpty(location) == false){
                    saveArea(location);
                }
            }
        });
        listview=(ListView) findViewById(R.id.myarea_listview);
        adapter=new MyAdapter();
        listview.setAdapter(adapter);
        isLocating = true;
        getPersimmions();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REGION_REQUEST_CODE && resultCode == 200) {
            if(data == null){
                return;
            }
            String province = data.getStringExtra(RegionSelectActivity.REGION_PROVINCE);
            String city = data.getStringExtra(RegionSelectActivity.REGION_CITY);
            String area = data.getStringExtra(RegionSelectActivity.REGION_AREA);
            saveArea(province + " " + city + " " + area);
        }
    }

    //保存地区信息
    private void saveArea(final String area){
        KyLoadingBuilder dialog = new KyLoadingBuilder(MyAreaActivity.this);
        dialog.setIcon(R.drawable.loading04);
        dialog.setText("正在保存...");
        dialog.setOutsideTouchable(false);//点击空白区域是否关闭
        dialog.setBackTouchable(true);//按返回键是否关闭
        dialog.show();
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
        map.put(APIKey.locationKey,area);
        HttpsUtils.changeuserinfoDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                dialog.dismiss();
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    ToastUtil.show(MyAreaActivity.this,"保存成功");
                    CustomApplication.loginModel.setLocation(area);
                    LogindbService.saveOrUpdateLogindbMode(CustomApplication.loginModel);
                    setResult(RESULT_OK);
                    finish();
                }else {
                    CustomApplication.showTip(commonModel,MyAreaActivity.this);
                }
            }

            @Override
            public void onError(String msg) {
                dialog.dismiss();
                ToastUtil.show(MyAreaActivity.this,"保存失败");
            }
        });
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private class MyAdapter extends BaseAdapter implements View.OnClickListener {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return 4;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View view=convertView;
            if (position == 0){
                view= LayoutInflater.from(MyAreaActivity.this).inflate(R.layout.myarea_listview_header, null);
            }else if (position == 1){
                view= LayoutInflater.from(MyAreaActivity.this).inflate(R.layout.myarea_listview_item1, null);
                TextView textView = (TextView) view.findViewById(R.id.myarea_listview_item1_text);
                if (isLocating == true){
                    textView.setText("正在定位...");
                }else {
                    textView.setText(location);
                }
            }else if (position == 2){
                view= LayoutInflater.from(MyAreaActivity.this).inflate(R.layout.myarea_listview_header, null);
            }else {
                view= LayoutInflater.from(MyAreaActivity.this).inflate(R.layout.myarea_listview_item2, null);
                TextView textView = (TextView) view.findViewById(R.id.myarea_listview_item2_text);
                textView.setClickable(true);
                textView.setOnClickListener(this);
            }
            return view;
        }

        // 监听事件实现
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.myarea_listview_item2_text:
                    Intent areaIntent = new Intent(MyAreaActivity.this, RegionSelectActivity.class);
                    startActivityForResult(areaIntent,REGION_REQUEST_CODE);
                    break;
                default:

                    break;
            }
        }
    }

    /**
     * 广播接收者
     * @author Gordon
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.print("onReceive接收到聊天广播了"+"\n");
            String action = intent.getAction();
            if (action.equals(BroadcastDefine.Get_Location)){
                String nation = intent.getStringExtra(APIKey.nationKey);
                String province = intent.getStringExtra(APIKey.provinceKey);
                String city = intent.getStringExtra(APIKey.cityKey);
                String area = intent.getStringExtra(APIKey.areaKey);
                String ilocation = intent.getStringExtra(APIKey.locationKey);
                System.out.print("定位的城市："+city+"\n");
                if (!CommonUtils.isEmpty(province)){
                    location += province;
                }
                if (!CommonUtils.isEmpty(city)){
                    if (location.length() > 0){
                        location += " ";
                    }
                    location += city;
                }
                if (!CommonUtils.isEmpty(area)){
                    if (location.length() > 0){
                        location += " ";
                    }
                    location += area;
                }
                if (location.length() == 0){
                    location = "当前无法定位";
                }else {
                    topbar.getRightTextView().setTextColor(getResources().getColor(R.color.mainColor));
                }
                isLocating = false;
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                }, 30);//30毫秒后执行Runnable中的run方法
            }

        }

    };

    /**
     * 注册广播
     * @author Gordon
     */
    public void registerBoradcastReceiver(){
        IntentFilter myIntentFilter = new IntentFilter();
        //添加接收广播类型
        myIntentFilter.addAction(BroadcastDefine.Get_Location);
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    //定位权限
    private void getPersimmions() {
        PermissionUtils.isLocationNote(MyAreaActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    ////判断当前是否是6.0版本
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        ArrayList<String> permissions = new ArrayList<String>();
                        /***
                         * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
                         */
                        // 定位精确位置
                        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);

                        }
                        if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);

                        }
                        if (permissions.size() > 0) {
                            requestPermissions(permissions.toArray(new String[permissions.size()]), 10000);
                        } else {//****这里写自己的定位调用***/////
                            ///当权限都有时，开始定位
                            CustomApplication.startLocation();
                        }
                    } else {
                        //****这里写自己的定位调用***/////
                        ///低于6.0以下，开始定位
                        CustomApplication.startLocation();
                    }
                }
            }
        });

    }

}
